# -*- coding: utf-8 -*-
"""
Created on Fri Oct  2 15:32:22 2020

@author: jyh
"""
import base64
import io
import os
"""
画数据分布
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from mpl_toolkits.mplot3d import Axes3D


def data_distri_plot(d, name):
    current_dir = os.path.dirname(os.path.abspath(__file__))

# 构造字体文件的完整路径
    font_path = os.path.join(current_dir, 'FZXBSJW.ttf')

# 加载字体
    my_font = fm.FontProperties(fname=font_path)
    my_size = 12
    my_font.set_size(my_size)
    
    fig = plt.figure(figsize=(6, 6))
    # ax = plt.gca(projection='3d')
    ax = fig.add_subplot(projection = '3d')
    for i in range(0, d.shape[1]):
        a, b = np.histogram(d[:, i], 256, [0, 256])
        # 计算总的频数
        total_count = a.sum()
        # 将频次转换为百分比
        a_percent = (a / total_count) * 100
    #    ax.bar(b[0:-1],a, zs=i, zdir='y', alpha=1)
        ax.plot3D(b[2: ], a_percent[1: ], zs=i, zdir='y')
        if d.shape[1] == 21:
            ax.yaxis.set_major_locator(plt.MultipleLocator(3))  #设置主要刻度
    
    
    ax.set_xlabel(u'字节取值(0~255)', fontproperties=my_font)
    ax.set_ylabel(u'字节偏移量', fontproperties=my_font)
    ax.set_zlabel('出现频率', fontproperties=my_font,rotation=90)
    plt.rcParams['axes.unicode_minus']=False
    plt.savefig(f'{name}.png', dpi=300,bbox_inches = 'tight') #指定分辨率保存
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    image_zhanshi = base64.b64encode(buf.getvalue()).decode('utf-8')
    plt.close()
    return image_zhanshi

if __name__ == "__main__":
    #import preprocess_1_data_load
    #data1,data2 = preprocess_1_data_load.load_data_payload(n_acars_pain=5000,L=10)
    import preprocess_out_data_load
    f = r"C:\Users\xieyifenxi\Desktop\经验\yyy.dat"
    data1=preprocess_out_data_load.read_file(f,1,10,2)
    data_distri_plot(data1)